package cn.lg.soar.system.account.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.util.FileUtil;
import cn.lg.soar.core.annotations.ResourceScanIgnore;
import cn.lg.soar.mvc.annotations.Log;
import cn.lg.soar.system.account.model.CodeLoginVo;
import cn.lg.soar.system.account.service.ICodeLoginService;
import cn.lg.soar.system.api.constant.ModuleConst;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@ResourceScanIgnore
@Api(tags = {"授权码登录"})
@RestController
@RequestMapping(ModuleConst.MODULE_NAME + "/code-login")
public class CodeLoginController {

    @Autowired
    private ICodeLoginService codeLoginService;

    @ApiOperation("生成授权二维码")
    @GetMapping(value = "generate-qrcode", name = "生成授权二维码")
    public HttpResult<String> generateQrcode(
            HttpServletRequest request,
            String format,
            @RequestParam(required = false, defaultValue = "300") int width,
            @RequestParam(required = false, defaultValue = "FFFFFF") String backColor,
            @RequestParam(required = false, defaultValue = "000000") String foreColor,
            @RequestParam(required = false, defaultValue = "1") int margin,
            @RequestParam(required = false, defaultValue = "false") Boolean toBase64,
            HttpServletResponse resp
    ) throws IOException {
        String content = codeLoginService.generate(request, format);
        QrConfig config = new QrConfig(width, width);
        config.setBackColor(Integer.parseInt(backColor, 16));
        config.setForeColor(Integer.parseInt(foreColor, 16));
        config.setMargin(margin);
        BufferedImage bufferedImage = QrCodeUtil.generate(content, config);
        if (toBase64) {
            return HttpResult.data(FileUtil.bufferedImageToBase64(bufferedImage));
        }
        FileUtil.bufferedImageToOut(bufferedImage, resp);
        return null;
    }

    @ApiOperation("生成授权码")
    @GetMapping(value = "generate", name = "生成授权码")
    public HttpResult<String> generate(HttpServletRequest request) {
        return HttpResult.data(codeLoginService.generate(request));
    }

    @Log(value = "授权授权码")
    @ApiOperation("授权授权码")
    @PostMapping(value = "handle", name = "授权授权码")
    public HttpResult<String> handle(@RequestBody CodeLoginVo vo) {
        codeLoginService.handle(vo);
        return HttpResult.success();
    }

}
